// pages/gouwuche/gouwuche.js

import {
  ajax,
  src,
  util
} from "../../utils/util.js";
Page({

  /**
   * 页面的初始数据
   */
  data: {
    navData: [{
      name: "首页", //文本
      index: 0, //是否是当前页，0不是  1是
      ico: '../images/tabbar/home-sy', //不同图标
      fn: 'gotoIndex', //对应处理函数
      width: 46,
      height: 46,
    }, {
      name: "订单",
      index: 1,
      ico: '../images/tabbar/home-dd',
      fn: 'gotoOrder',
      width: 44,
      height: 44,
    }, {
      name: "自提",
      index: 2,
      ico: '../images/tabbar/home-zt',
      fn: 'gotoSelfhelp',
      width: 44,
      height: 44,
    }, {
      name: "我的",
      index: 3,
      ico: '../images/tabbar/home-wd',
      fn: 'gotoMine',
      width: 40,
      height: 44,
    }, ],
    current: 0,
    currentdd: 1,

    allcarlist: '',
    gengduo: true,
    currentpage: 0,
    jiazaizhong: false,

    zitilist: ""
  },
  whenchange: function(e) {
    var currentdd = e.detail.current + 1
    this.setData({
      currentdd: currentdd
    })
  },

  gotoIndex: function() {
    wx.reLaunch({
      url: '/pages/index/index',
    })
  },
  gotoOrder: function() {
    wx.reLaunch({
      url: '/pages/order/order',
    })
  },
  gotoSelfhelp: function() {
    wx.reLaunch({
      url: '/pages/selfhelp/selfhelp',
    })
  },
  gotoMine: function() {
    wx.reLaunch({
      url: '/pages/mine/mine',
    })
  },
  getallcar: function(PageIndex) {
    ajax('/api/ShopCart/GetCart?requestContent=' + JSON.stringify({
      token: wx.getStorageSync('Access_token'),
      PageIndex: PageIndex
    }), {
      header: {
        'Accept': 'application/x-www-form-urlencoded', // 默认值
      },
      method: "get",
    }, res => {
      // console.log(res)


      for (var x in res.Models) {
        for (var y in res.Models[x].data) {
          res.Models[x].data[y].fuindex = x
        }
        res.Models[x].allmoney = 0
      }

      for (var x in res.Models) {
        if (this.jianceselectall(res.Models[x].data)) {
          res.Models[x].selectall = true
        } else {
          res.Models[x].selectall = false
        }
      }

      // console.log(res.Models)

      if (PageIndex == 0) {

        if (res.Models != null) {
          this.setData({
            allcarlist: res.Models,
            maxnum: res.Models[0].ProductNums
          })
          this.jisuanallmoney()
          if (res.Models.length == 10) {
            if (res.Models[0].ProductNums > 10) {
              this.setData({
                gengduo: true
              })

            } else {
              this.setData({
                gengduo: false
              })
            }
          } else {
            this.setData({
              gengduo: false
            })
          }

        } else {
          this.setData({
            allcarlist: null,
            gengduo: false
          })
        }
      } else {


        var add = res.Models
        var allcarlist = this.data.allcarlist
        for (var x in add) {
          allcarlist.push(add[x])
        }

        this.setData({
          allcarlist: allcarlist,
          maxnum: res.Models[0].ProductNums
        })
        this.jisuanallmoney()

        if (res.Models.length == 10) {
          if (res.Models[0].ProductNums > allcarlist.length) {
            this.setData({
              gengduo: true
            })
          } else {
            this.setData({
              gengduo: false
            })
          }
        } else {
          this.setData({
            gengduo: false
          })
        }
      }


      if (this.data.jiazaizhong) {
        this.setData({
          jiazaizhong: false
        })
      }
     
    })
  },


  getselfhelplist: function() {
    ajax('/api/OrderALLORCode/Get?requestContent=' + JSON.stringify({

      token: wx.getStorageSync("Access_token")
    }), {
      header: {
        'Accept': 'application/x-www-form-urlencoded', // 默认值
      },
      method: "get",
    }, res => {
      console.log(res)
      this.setData({
        zitilist: res.Models
      })

    })
  },

  tojiesuan: function(e) {
    var fuindex = e.currentTarget.dataset.index

    // var query":[{"DealerID":39,"Orders":[{"PGID":372,"SKUID":733,"OrderNumber":1}]}],"
    var query = []
    var CartIDStr = ""
    var CartIDStrlist = []

    var DealerID = this.data.allcarlist[fuindex].key
    var objhu = {}
    var Orders = []
    objhu.DealerID = DealerID

    for (var x in this.data.allcarlist[fuindex].data) {
      if (this.data.allcarlist[fuindex].data[x].IsChecked) {
        var obj = {}
        obj.PGID = this.data.allcarlist[fuindex].data[x].ProuductPublishID
        obj.SKUID = this.data.allcarlist[fuindex].data[x].SKUID
        obj.OrderNumber = this.data.allcarlist[fuindex].data[x].OrderNumber
        Orders.push(obj)
        CartIDStrlist.push(this.data.allcarlist[fuindex].data[x].CartID)
      }
    }
    objhu.Orders = Orders
    query.push(objhu)
    CartIDStr = CartIDStrlist.join(",")

    ajax('/api/ShopCart/UpdateState?requestContent=' + JSON.stringify({
      token: wx.getStorageSync('Access_token'),
      CartIDStr: CartIDStr,
      query: query
    }), {
      header: {
        'Accept': 'application/x-www-form-urlencoded', // 默认值
      },
      method: "post",
    }, res => {
      console.log(res)
      if (res.Message == "上传成功!") {
        wx.navigateTo({
          url: '/pages/sureorder/sureorder?CartIDStr=' + CartIDStr,
        })
      } else {
        wx.showToast({
          title: res.Message,
          icon: 'none',
          duration: 2000
        })
      }
      // console.log("11111111111111111111111111111")

    })
  },

  jisuanallmoney: function() {
    for (var x in this.data.allcarlist) {
      var allmoney = 0
      for (var y in this.data.allcarlist[x].data) {
        if (this.data.allcarlist[x].data[y].IsChecked == true) {
          var dange = this.data.allcarlist[x].data[y].IMoney * 100
          dange = dange * this.data.allcarlist[x].data[y].OrderNumber
          // dange=dange/100
          console.log(dange)
          allmoney = allmoney * 100
          allmoney = allmoney + dange
          allmoney = allmoney / 100
        }
      }

      console.log(allmoney)

      var str = "allcarlist[" + x + "].allmoney"
      this.setData({
        [str]: allmoney.toFixed(2)
      })
    }
  },

  lower: function() {
    if (this.data.jiazaizhong) {
      return
    }
    if (this.data.gengduo) {
      this.setData({
        jiazaizhong: true,
        currentpage: this.data.currentpage + 1
      })

      this.getallcar(this.data.currentpage * 10)
    } else {
      return
    }

   

  },


  // #########################################################
  // CARLIST
  updatacarnum: function(index, fuindex, VType) {
    ajax('/api/ShopCart/UpdateNums?requestContent=' + JSON.stringify({
      token: wx.getStorageSync('Access_token'),
      ShopID: this.data.ID,

      SKUID: this.data.allcarlist[fuindex].data[index].SKUID,
      ProuductPublishID: this.data.allcarlist[fuindex].data[index].ProuductPublishID,
      OrderNumber: VType == 1 ? this.data.allcarlist[fuindex].data[index].OrderNumber + 1 : this.data.allcarlist[fuindex].data[index].OrderNumber - 1,
      ID: this.data.allcarlist[fuindex].data[index].CartID,
      VType: VType
    }), {
      header: {
        'Accept': 'application/x-www-form-urlencoded', // 默认值
      },
      method: "post",
    }, res => {
      console.log(res)
      if (res.Message == "库存不足") {
        wx.showToast({
          title: res.Message,
          icon: 'none',
          duration: 1000
        })
      }
      this.getallcar(0)
      // this.getnr()
    })
  },

  //car add
  caradd: function(e) {
    var index = e.currentTarget.dataset.index
    var fuindex = e.currentTarget.dataset.fuindex
    this.updatacarnum(index, fuindex, 1)
  },
  carminus: function(e) {
    var index = e.currentTarget.dataset.index
    var fuindex = e.currentTarget.dataset.fuindex
    this.updatacarnum(index, fuindex, 2)
  },
  // ###########################

  selectall: function(e) {
    var fuindex = e.currentTarget.dataset.index
    var that = this
    // console.log(!this.data.allcarlist[index].selectall)
    var selectall = !that.data.allcarlist[fuindex].selectall
    for (var index in that.data.allcarlist[fuindex].data) {

      // console.log(index, fuindex)
      that.updatedichecked(index, fuindex, selectall)
    }
  },

  jianceselectall: function(data) {
    for (var x in data) {
      if (data[x].IsChecked == false) {
        return false
      }
    }
    return true
  },


  updatedichecked: function(index, fuindex, IsChecked) {
    ajax('/api/ShopCart/UpdateChecked?requestContent=' + JSON.stringify({
      token: wx.getStorageSync('Access_token'),
      IsChecked: IsChecked,
      CartIDStr: this.data.allcarlist[fuindex].data[index].CartID
    }), {
      header: {
        'Accept': 'application/x-www-form-urlencoded', // 默认值
      },
      method: "post",
    }, res => {
      console.log(res)
      this.getallcar(0)

    })
  },



  clickdanxuan: function(e) {
    var index = e.currentTarget.dataset.index
    var fuindex = e.currentTarget.dataset.fuindex

    // console.log(index)
    // console.log(fuindex)

    this.updatedichecked(index, fuindex, !this.data.allcarlist[fuindex].data[index].IsChecked)
  },


  //清空/删除购物车
  clearcart() {
    ajax('/api/ShopCart/DelCart?requestContent=' + JSON.stringify({
      token: wx.getStorageSync('Access_token'),
      Type: 1,
    }), {
      header: {
        'Accept': 'application/x-www-form-urlencoded', // 默认值
      },
      method: "post",
    }, res => {
      console.log(res)
      this.setData({
        allcarlist: []
      })
      this.getallcar(0)

    })
  },
  // / 删除购物车
  delcart() {
    var CartIDStr
    var CartIDStrlist = []
    for (var x in this.data.allcarlist) {
      for (var y in this.data.allcarlist[x].data) {
        if (this.data.allcarlist[x].data[y].IsChecked == true) {
          CartIDStrlist.push(this.data.allcarlist[x].data[y].CartID)
        }
      }
    }
    CartIDStr = CartIDStrlist.join(",")
    ajax('/api/ShopCart/DelCart?requestContent=' + JSON.stringify({
      token: wx.getStorageSync('Access_token'),
      CartIDStr: CartIDStr,
      Type: 2,
    }), {
      header: {
        'Accept': 'application/x-www-form-urlencoded', // 默认值
      },
      method: "post",
    }, res => {
      console.log(res)
      this.setData({
        allcarlist: []
      })
      this.getallcar(0)

    })
  },


  toshophomepage: function(e) {

    wx.navigateTo({
      url: '/pages/shop-homepage/homepage?ID=' + e.currentTarget.dataset.id,
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    wx.setNavigationBarColor({
      frontColor: '#ffffff',
      backgroundColor: '#000',
    })
    this.getallcar(0)
    this.getselfhelplist()

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    this.getallcar(0)
    this.getselfhelplist()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})